<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "news".
 *
 * @property integer $id
 * @property integer $type
 * @property integer $author_id
 * @property integer $country_id
 * @property integer $role
 * @property string $title
 * @property string $content
 * @property string $time
 * @property string $create_at
 * @property string $update_at
 *
 * @property User $author
 * @property Country $country
 */
class News extends \app\models\BaseModel {
    const TYPE_NEWS = 1;
    const TYPE_NOTICE = 2;
    public static $roles = [
        self::TYPE_NEWS => '新闻',
        self::TYPE_NOTICE => '公告',
    ];

    /**
     * @inheritdoc
     */
    public static function tableName() {
        return 'news';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['type', 'author_id', 'title', 'content', 'time'], 'required'],
            [['type', 'author_id', 'country_id', 'role'], 'integer'],
            [['time', 'create_at', 'update_at'], 'safe'],
            [['title', ], 'string', 'max' => 255],
            [['content'], 'string'],
            [['author_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['author_id' => 'id']],
            [['country_id'], 'exist', 'skipOnError' => true, 'targetClass' => Country::className(), 'targetAttribute' => ['country_id' => 'id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => '公告id',
            'type' => '类型，新闻或者公告',
            'author_id' => '公告作者',
            'country_id' => 'Country ID',
            'role' => 'Role',
            'title' => '公告标题',
            'content' => '公告内容',
            'time' => '公告时间',
            'create_at' => '创建时间',
            'update_at' => '更新时间',
        ];
    }

    public function fields() {
        $fields = [
            'id',
            'type',
            'role',
            'title',
            'content',
            'time',
            'author',
            'country',
        ];
        $fields = array_combine($fields, $fields);

        return $fields;
    }

    public function extraFields() {
        $fields = [
            'author_id',
            'country_id',
            'create_at',
            'update_at',
        ];
        $fields = array_combine($fields, $fields);
        return $fields;
    }

    public function getAuthor() {
        return $this->hasOne(User::className(), ['id' => 'author_id'])->inverseOf('news');
    }

    public function getCountry() {
        return $this->hasOne(Country::className(), ['id' => 'country_id'])->inverseOf('news');
    }
}
